package com.iweb;

import com.alibaba.fastjson2.JSONObject;
import com.iweb.pojo.Goods;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet(name = "GoodsServlet",urlPatterns = "/goods")
public class GoodsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");
        //接收请求参数
        String name = req.getParameter("name");
        //模拟 service和mapper实现去数据库查询初Goods
        ArrayList<Goods> goods = new ArrayList<>();
        goods.add(new Goods(1,"白菜","南通",0.26));
        goods.add(new Goods(2,"芹菜","合肥",12));
        goods.add(new Goods(3,"手机","绍兴",1999));
        goods.add(new Goods(4,"电脑","南阳",2444));
        goods.add(new Goods(5,"衣服","鹤壁",125));
        goods.add(new Goods(6,"袜子","济南",12));
        //前后端交互的数据格式 json
        //goods--String  json格式返回
        //返回一个新的结果
        ArrayList<Goods> list = new ArrayList<>();
        for (Goods g:goods){
            if (g.getName().equals(name)){
                list.add(g);
            }
        }
        String data = JSONObject.toJSONString(list);
        resp.getWriter().write(data);

    }
}
